<?php

namespace youmbe\phpword;

use PhpOffice\PhpWord\Exception\Exception;

/**
 * Description of newPHPClass
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class WordIOFactory extends \PhpOffice\PhpWord\IOFactory {

    private static $extensions = [
        'ODText' => 'odt',
        'RTF' => 'rtf',
        'Word2007' => 'docx',
        'HTML' => 'html',
        'PDF' => 'pdf'
    ];

    /**
     * Create new writer
     *
     * @param string $name
     * @param string $format
     *
     * @throws \PhpOffice\PhpWord\Exception\Exception
     *
     * @return WriterInterface
     */
    public static function buildFileName($name = '', $format = 'Word2007') {
        if (!$name) {
            $name = 'export';
        }
        if (strpos($name, '.') === false) {
            if (!in_array($format, array_keys(self::$extensions), true)) {
                throw new Exception("\"{$format}\" is not a valid writer.");
            }
            $ext = self::$extensions[$format];
        } else {
            $info = pathinfo($name);
            $ext = $info['extension'];
            if (!in_array($ext, self::$extensions, true)) {
                throw new Exception("\"{$ext}\" is not a valid format.");
            }
            $name = basename($name, '.' . $ext);
        }
        return $name . '.' . $ext;
    }

}
